/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        //新建子函数用于递归
        //用四个指针分别表示左右子树在两个遍历中的起始点
        int preStart = 0;
        int preEnd = preorder.size() - 1;
        int inStart = 0;
        int inEnd = inorder.size() - 1;
        return binaryTree(preorder, inorder, preStart, preEnd, inStart, inEnd);
    }

    TreeNode * binaryTree(
        vector<int>& preorder, vector<int>& inorder,
        int preStart, int preEnd, int inStart,int inEnd
    )
    {
        if((preStart > preEnd) || (inStart > inEnd))  return NULL;  //子树为空
        TreeNode * root = new TreeNode(preorder[preStart]);
        //寻找位于中序遍历中的根节点位置
        int middle = inStart;
        for(; middle <= inEnd; ++middle) {
            if( inorder[middle] == preorder[preStart])  break;
        }
        root->left = binaryTree(
            preorder, inorder, preStart + 1, preStart + middle - inStart, inStart, middle - 1);
        root->right = binaryTree(
            preorder, inorder, preEnd - (inEnd - middle) + 1, preEnd, middle + 1, inEnd);
        return root;
    }
};